using CSharpX;
using System;
using System.Threading.Tasks;
using UnityEngine;

public class UITransparentAnimation
{
    public event Action onPlayEnd;

    private bool playing = false;
    private float m_AnimationBeginTime;
    private float m_BeginValue;
    private float m_EndValue;
    private float duration = 1f;
    private float curve = 0.5f;
    private CanvasGroup m_CanvasGroup;
    private GameObject gameObject;

    public UITransparentAnimation(GameObject gameObject)
    {
        this.gameObject = gameObject;
    }
    public void Play(float m_BeginValue, float m_EndValue, float duration, float curve)
    {
        CheckCanvasGroup();
        m_AnimationBeginTime = Time.time;
        this.m_BeginValue = m_BeginValue;
        this.m_EndValue = m_EndValue;
        this.duration = duration;
        this.curve = curve;

        if (!playing)
        {
            playing = true;
            PlayUpdate();
        }
    }
    private void CheckCanvasGroup()
    {
        if (m_CanvasGroup == null)
        {
            m_CanvasGroup = gameObject.GetComponent<CanvasGroup>();
            if (m_CanvasGroup == null)
            {
                m_CanvasGroup = gameObject.AddComponent<CanvasGroup>();
            }
        }
    }
    private async void PlayUpdate()
    {
        while (playing)
        {
            float elapsedTime = Time.time - m_AnimationBeginTime;
            if (elapsedTime < duration)
            {
                float t = Curve.X3(curve, elapsedTime / duration);
                m_CanvasGroup.alpha = Mathf.Lerp(m_BeginValue, m_EndValue, t);
            }
            else
            {
                playing = false;
                m_CanvasGroup.alpha = m_EndValue;
                onPlayEnd?.Invoke();
                return;
            }
            await Task.Yield();
#if UNITY_EDITOR
            if (!UnityEditor.EditorApplication.isPlaying)
            {
                playing = false;
                return;
            }
#endif
        }
    }
}
